package com.cms.room

import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.arouter.ArouterContains
import com.android.baselibrary.base.BaseActivity
import com.cms.room.databinding.ActivityRoomMainBinding
@Route(path = ArouterContains.ROOM_MODEL)
class RoomMainActivity : BaseActivity<ActivityRoomMainBinding>(), View.OnClickListener {

    private val viewModel: RoomViewModel by lazy {
        ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application))[RoomViewModel::class.java]
    }

    override fun getLayoutId(): Int = R.layout.activity_room_main

    override fun initView() {
        mBinding.listener = this
    }

    override fun initListener() {
        val roomAdapter = RoomAdapter()
        mBinding.recycle.adapter = roomAdapter
        viewModel.queryStudent().observe(this) {
            roomAdapter.setData(it.toMutableList())
        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            /**新增**/
            R.id.btn_add -> {
                if (mBinding.edAge.text.isNullOrEmpty()||mBinding.edName.text.isNullOrEmpty()) return
                viewModel.insertStudent(Student().apply { name = mBinding.edName.text.toString()
                    age = mBinding.edAge.text.toString().toIntOrNull()?:0
                })
            }
            /**删除**/
            R.id.btn_delete -> {
                if (mBinding.edAge.text.isNullOrEmpty()||mBinding.edName.text.isNullOrEmpty()) return
                viewModel.deleteStudent(Student().apply { name = mBinding.edName.text.toString()
                    age = mBinding.edAge.text.toString().toIntOrNull()?:0
                })
            }
            /**更新**/
            R.id.btn_update -> {
                if (mBinding.edAge.text.isNullOrEmpty()||mBinding.edName.text.isNullOrEmpty()) return
                viewModel.updateStudent(Student().apply { name = mBinding.edName.text.toString()
                    age = mBinding.edAge.text.toString().toIntOrNull()?:0
                })
            }
            /**查询**/
            R.id.btn_query -> {
                viewModel.queryStudent()
            }
        }
    }

}